#!/bin/sh

GIT_ADDRESS=$2
PROJECT_NAME=$1
BRANCH=$3
CONFIGURATION=$4
VERSION=$5
BUILD_NUM=$6
BUNDLE_ID=$7
PACKAGE_ID=$8
UPLOAD_URL=$9
GIT_PATH=${10}

export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8
export LC_ALL=en_US.UTF-8

CURRENT_USER=`whoami`
if [ `uname` == 'Linux' ]; then
  USER_DIR=/home
elif [ `uname` == 'Darwin' ]; then
  USER_DIR=/Users
fi

source ${USER_DIR}/${CURRENT_USER}/.bash_profile

GIT_BASE_PATH=${USER_DIR}/${CURRENT_USER}/iPack/Android/Archive/${PROJECT_NAME}/${BRANCH}
if [ ! -d ${GIT_BASE_PATH} ];then
  mkdir -p ${GIT_BASE_PATH}
fi

cd ${GIT_BASE_PATH}

if [ ${#GIT_PATH} != 0 ];then
  to_project_path=${GIT_BASE_PATH}/${GIT_PATH}
else
  to_project_path=${GIT_BASE_PATH}
fi

ASSEMBLE_INFO=`echo $CONFIGURATION | awk '{for(i=1;i<=NF;i++) {printf "%s%s ", toupper(substr($i,1,1)),substr($i,2)};printf ORS}'`

if [ ! -d ${to_project_path}/${PROJECT_NAME} ]; then
  git clone -b ${BRANCH} ${GIT_ADDRESS}
  if [ $? != 0  ]
  then
  echo '拉取代码失败'
  exit 1
  fi
  cd ${to_project_path}/${PROJECT_NAME}
  chmod +x ./gradlew
  ./gradlew clean assemble${ASSEMBLE_INFO} -Pversion=${VERSION}.${BUILD_NUM}
  if [ $? != 0  ]
  then
  echo '打包(gradlew)失败'
  exit 1
  fi
else
  cd ${to_project_path}/${PROJECT_NAME}
  git checkout .
  git pull
  if [ $? != 0  ]
  then
  echo '拉取代码失败'
  exit 1
  fi
  echo
  ./gradlew assemble${ASSEMBLE_INFO} -Pversion=${VERSION}.${BUILD_NUM}
  if [ $? != 0  ]
  then
  echo '打包(gradlew)失败'
  exit 1
  fi
fi

#关掉gradle daemon并释放内存
#./gradlew --stop
sync

function getdir(){
    for element in `ls $1`
    do
        dir_or_file=$1"/"$element
        if [ -d $dir_or_file ]
        then
            getdir $dir_or_file
        else
            apk_file=`echo $dir_or_file|rev|cut -c-4|rev`
            if [ $apk_file == '.apk' ]; then
                echo ${dir_or_file}
            fi

        fi
    done
}
files=`getdir ./app/build/outputs/apk`
last_file=`echo $files | cut -d' ' -f1`
if [ ! -d ${USER_DIR}/${CURRENT_USER}/iPack/Android/Packages ]; then
  mkdir -p ${USER_DIR}/${CURRENT_USER}/iPack/Android/Packages
fi
echo ${last_file}
mv ${last_file} ${USER_DIR}/${CURRENT_USER}/iPack/Android/Packages/${BUNDLE_ID}-${VERSION}-${BUILD_NUM}.apk
rm -rf ${to_project_path}/${PROJECT_NAME}/app/build/outputs/apk

apkFile=${USER_DIR}/${CURRENT_USER}/iPack/Android/Packages/${BUNDLE_ID}-${VERSION}-${BUILD_NUM}.apk

result=`curl -F "package=@${apkFile}" -F "package_id=${PACKAGE_ID}" ${UPLOAD_URL}/package/upload`;
echo $result
rightContent=`echo $result | grep '^{' | grep '}$'`
if [ ${#rightContent} == 0 ]; then
  echo '上传文件出现问题';
  exit 1
else
  code=$(echo -e ${result//,/\\n} | grep 'code' | cut -d : -f 2)
  echo -e $code
  if [ $code == 0 ]
  then
      exit 0
  else
      echo -e ${result//,/\\n} | grep 'message' | cut -d : -f 2
      exit 1
  fi
fi
